package com.atguigu.lease.web.admin.service.impl;


import com.atguigu.lease.common.minio.MinioProperties;
import com.atguigu.lease.web.admin.service.FileService;
import io.minio.*;
import io.minio.errors.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@Service
public class FileServiceImpl implements FileService {

    @Autowired
    private MinioClient client;
    @Autowired
    private MinioProperties properties;

    @Override
    public String upload(MultipartFile file) throws ServerException, InsufficientDataException, ErrorResponseException, IOException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {
        boolean bucketExists = client.bucketExists(
                BucketExistsArgs.builder()
                        .bucket(properties.getBucketName())
                        .build());
        if (!bucketExists) {
            client.makeBucket(
                    MakeBucketArgs.builder()
                            .bucket(properties.getBucketName())
                            .build());
            client.setBucketPolicy(
                    SetBucketPolicyArgs.builder()
                            .bucket(properties.getBucketName())
                            .config(createBucketPolicyConfig(properties.getBucketName()))
                            .build());
        }
        //todo 获取上传文件的文件名
        String originalFilename = file.getOriginalFilename();
        //todo 获取上传文件的后缀名
        String suffixName = originalFilename.substring(originalFilename.lastIndexOf("."));
        //todo 将UUID作为新的文件名
        originalFilename = UUID.randomUUID() + suffixName;
        String filename = new SimpleDateFormat("yyyyMMdd")
                .format(new Date()) + "/" + originalFilename;
//                UUID.randomUUID() + "-" + file.getOriginalFilename();
        client.putObject(
                PutObjectArgs.builder()
                        //todo 设置桶的名字
                        .bucket(properties.getBucketName())
                        //todo 设置上传文件文件名字
                        .object(filename) //设置上传文件文件名字
                        //todo 设置上传的文件 -1 ： 上传文件所有内容
                        .stream(file.getInputStream(), file.getSize(), -1)
                        //todo 上传文件类容格式
                        .contentType(file.getContentType())
                        .build());

        return String
                //todo 拼接 服务器地址 桶名 文件名
                .join("/", properties.getEndpoint(), properties.getBucketName(), filename);
    }

    private String createBucketPolicyConfig(String bucketName) {

        return """
                {
                  "Statement" : [ {
                    "Action" : "s3:GetObject",
                    "Effect" : "Allow",
                    "Principal" : "*",
                    "Resource" : "arn:aws:s3:::%s/*"
                  } ],
                  "Version" : "2012-10-17"
                }
                """.formatted(bucketName);
    }
}
